
<template>
  <view class="page">
    <!-- 头部导航 -->
    <view class="header">
      <uni-icons type="back" size="24" color="#333333" class="back-icon" />
      <text class="title">专业详情</text>
      <uni-icons type="more-filled" size="24" color="#333333" class="more-icon" />
    </view>

    <!-- 课程概览 -->
    <view class="course-overview">
      <view class="overview-left">
        <text class="course-title">{{category.categoryName}}</text>
        <text class="course-desc">总时长: --小时 | 评分: -- | 最新版: v3.0</text>
      </view>
	 <view class="overview-right">
		  
		  <!-- <image class="ai-icon" :src="aiIconUrl" mode="aspectFill" /> -->
		</view>
    </view>
	  <view class="price-button">
	    <text class="price-text"  @click="toOrder(treeData.totalPrice,category.categoryName)">购买此专业 ({{treeData.totalPrice}}元)</text>
	  </view>
    <!-- 课程列表 -->
    <scroll-view class="course-list" scroll-y>
      <view class="course-section" v-for="(section, index) in treeData.children" :key="index">
        <view class="section-header">
          <text class="section-title">{{ section.title }}</text>
          <text class="section-info">共计: {{ treeData.children.length }}门课</text>
        </view>
        <view class="section-price" @click="toOrder(section.totalPrice,section.title)">
          <text class="price-label" >购买此阶段 ({{ section.totalPrice }}元)</text>
        </view>
        
        <view class="course-cards">
          <view  v-for="(course, cIndex) in section.children" :key="cIndex">
			  <view class="course-card" @tap="toDeatl(course)">
				  <view class="card-left">
				  	<img  class="ai-icon"  src="https://ai-public.mastergo.com/ai/img_res/e0ab13f7a22863423628cc0c4a7b3ade.jpg" draggable="false">
				      <!-- <image class="course-icon" :src="course.iconUrl" mode="aspectFill" /> -->
				    </view>
				    <view class="card-right">
				      <text class="card-title">{{ course.title }}</text>
				  			  <text class="card-desc">课程描述</text>
				      <!-- <text class="card-desc">{{ course.description }}</text> -->
				      <view class="card-stats">
				        <view class="views">
				          <uni-icons type="eye" size="14" color="#666666" />
				          <text class="view-count">----次观看</text>
				        </view>
				        <text v-if="course.price" class="course-price">{{ course.totalPrice }}</text>
				  				<view v-for="item in course.children">
				  					 <text class="view-count">{{item.title}}</text>
				  					  <text class="view-count">{{item.price}}</text>
				  				</view>
				      </view>
				    </view>
				  
			  </view>
          </view>
        </view>
      </view>
    </scroll-view>
   <view class="pay-container" v-show="ifclick">
    <view class="pay-mask"  @click="closeOrder"></view>
    <view class="pay-content">
      <view class="pay-title">结算台</view>
      <view class="pay-notice">该课程是付费课程，您需要先按实际授课才能使用相关内容</view>
      <view class="pay-info">
        <uni-text class="info-name">{{pagcontent.name}}</uni-text>
        <uni-text class="info-price">{{pagcontent.moneny}}元</uni-text>
      </view>
      <view class="pay-actions">
        <uni-button class="action-btn alipay" @click="handleAlipay">支付宝支付</uni-button>
      </view>
      <view class="pay-tips">
       小小提示 提示词暂未想好 这里采用沙盒
      </view>
    </view>
  </view>
  </view>

</template>

<script lang="ts" setup>
import { onLoad } from '@dcloudio/uni-app'
import { onMounted, ref} from 'vue';
import { getChapterById } from '@/pages/utils/api/clazz.js'
import { createOrder } from '@/pages/utils/api/order';
import { useUserStore  } from'@/stores/api.js'
const errorMessage = ref('');
const userStore = useUserStore ();
const aiIconUrl = 'https://ai-public.mastergo.com/ai/img_res/9c2cda92479b7dc926ab707cb410b836.jpg';
const treeData = ref([]);
let paymentAmount="";
const pagcontent=ref({  
	moneny:"",
	name:''
})
const ifclick=ref(false);
let  category ={};

const getChapter =  async ( categoryId: any ) =>{

	try {
	  let data ={
		  parentCategoryId : categoryId-0
	  }; 
	  const res = await getChapterById(data);
	  let re = transformToTree(res.data);
      treeData.value = re[0];
	  console.log('transformToTree', treeData.value)
	} catch (error) {
	  console.log('获取数据失败', error)
	}
}
function getCatergin(){
	
}
// 点击支付 
const handleAlipay =async ()=>{
	// amendName
	// courseId
	// notes
	// paymentAmount
	// paymentStatus
	// userId

	console.log("useUserStore",userStore.userInfo)
	try{
		if(userStore.userInfo.userId ==null ||  userStore.userInfo.userId ==undefined ){
			 errorMessage.value = '加载支付页面失败';
			 return;
		}
		// 生成订单
		let data={
			userId:userStore.userInfo.userId,
			courseId:'',
			paymentAmount:paymentAmount,
			paymentStatus:"待付款",
			amendName:userStore.userInfo.amendName,
			notes: "",
		}
		 const res = await createOrder(data);
		
	}catch(error){
		 console.log('新增失败', error)
	}
}
function toDeatl(item ){
	console.log("点击卡片",item );
	uni.navigateTo({
	  url: "/pages/clazz/index?courseId="+item.courseId+"&title=" + item.title + "&description="+item.originalData.description,
	  fail: (err) => {
	    console.log('跳转失败详情:', err);
	    uni.showToast({
	      title: '跳转失败: ' + err.errMsg,
	      icon: 'none'
	    });
	  },
	  success: () => {
	    console.log('跳转成功');
	  }
	});
	
}
function closeOrder(){
	ifclick.value=false;
}
function toOrder( moneny,name){
    paymentAmount = moneny;
	ifclick.value=true;
	pagcontent.value.moneny=moneny;
	pagcontent.value.name=name;
}
function transformToTree(courseData) {
  // 第一层：汇总所有课程
  const rootNode = {
    title: '所有课程',
    key: 'all-courses',
    children: [],
    totalPrice: 0 // 初始化总价格
  };

  // 用对象来暂存阶段分组
  const stageMap = {};

  // 遍历所有课程数据
  courseData.forEach(course => {
    const stageName = course.chapterNames || '未分类阶段';
    
    // 如果阶段不存在，则创建
    if (!stageMap[stageName]) {
      stageMap[stageName] = {
        title: stageName,
        key: `stage-${stageName}`,
        children: [],
        totalPrice: 0
      };
      rootNode.children.push(stageMap[stageName]);
    }

    // 创建课程节点
    const courseNode = {
      title: `${course.courseName} `,
      key: `course-${course.courseId}`,
      isLeaf: true,
      price: course.price,
      courseId: course.courseId,
      originalData: course // 保留原始数据
    };

    // 添加到对应阶段
    stageMap[stageName].children.push(courseNode);
    stageMap[stageName].totalPrice += course.price;
    rootNode.totalPrice += course.price;
  });

  // 为每个阶段节点添加价格显示
  rootNode.children.forEach(stage => {
    stage.title = `${stage.title} `;
  });

  // 为根节点添加价格显示
  rootNode.title = `${rootNode.title} (¥${rootNode.totalPrice})`;

  return [rootNode]; // 返回数组形式，符合树形组件通常的预期
}

// 使用示例
const jsonData = {
  "code": 200,
  "message": "操作成功",
  "data": [
    // 您提供的课程数据...
  ]
};
onMounted(()=>{
	// console.log('页面参数:', options.categoryId);
	getChapter(category);
})
onLoad( (options)=> {
 category = options.categoryId;
})
</script>

<style>
page {
  height: 100%;
  background-color: #f5f5f5;
}

.page {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
  padding: 0 32rpx;
  background-color: #ffffff;
  border-bottom: 1px solid #f0f0f0;
}

.title {
  font-size: 16px;
  font-weight: 500;
  color: #333333;
}

.back-icon, .more-icon {
  width: 48rpx;
  height: 48rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.course-overview {
  display: flex;
  padding: 32rpx;
  background-color: #ffffff;
  margin-bottom: 20rpx;
}

.overview-left {
  flex: 1;
  margin-right: 32rpx;
}

.course-title {
  font-size: 20px;
  font-weight: 600;
  color: #333333;
  margin-bottom: 16rpx;
  display: block;
}

.course-desc {
  font-size: 14px;
  color: #666666;
  margin-bottom: 32rpx;
  display: block;
}

.price-button {
  background-color: #2979ff;
  border-radius: 8rpx;
  padding: 24rpx 0;
  text-align: center;
}

.price-text {
  color: #ffffff;
  font-size: 16px;
  font-weight: 500;
}

.overview-right {
  width: 120rpx;
  height: 120rpx;
  flex-shrink: 0;
}

.ai-icon {
  width: 100%;
  height: 100%;
  border-radius: 60rpx;
}

.course-list {
  flex: 1;
  overflow: auto;
}

.course-section {
  background-color: #ffffff;
  margin-bottom: 20rpx;
  padding: 32rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #333333;
}

.section-info {
  font-size: 14px;
  color: #999999;
}

.section-price {
  background-color: #f5f7fa;
  padding: 24rpx;
  border-radius: 8rpx;
  margin-bottom: 32rpx;
}

.price-label {
  font-size: 14px;
  color: #666666;
}

.course-card {
  display: flex;
  padding: 24rpx 0;
  border-bottom: 1px solid #f0f0f0;
}

.course-card:last-child {
  border-bottom: none;
}

.card-left {
  width: 96rpx;
  height: 96rpx;
  margin-right: 24rpx;
  flex-shrink: 0;
}

.course-icon {
  width: 100%;
  height: 100%;
  border-radius: 16rpx;
}

.card-right {
  flex: 1;
}

.card-title {
  font-size: 16px;
  color: #333333;
  margin-bottom: 8rpx;
  display: block;
}

.card-desc {
  font-size: 14px;
  color: #666666;
  margin-bottom: 16rpx;
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.card-stats {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.views {
  display: flex;
  align-items: center;
}

.view-count {
  font-size: 12px;
  color: #999999;
  margin-left: 8rpx;
}

.course-price {
  font-size: 14px;
  color: #ff6b00;
  font-weight: 500;
}
.pay-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

.pay-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.6);
}

.pay-content {
  position: relative;
  width: 600rpx;
  background-color: #ffffff;
  border-radius: 24rpx;
  padding: 40rpx;
}

.pay-title {
  font-size: 18px;
  color: #333333;
  font-weight: 500;
  text-align: center;
  margin-bottom: 30rpx;
}

.pay-notice {
  font-size: 14px;
  color: #666666;
  line-height: 1.4;
  margin-bottom: 40rpx;
}

.pay-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40rpx;
}

.info-name {
  font-size: 16px;
  color: #333333;
}

.info-price {
  font-size: 16px;
  color: #333333;
  font-weight: 500;
}

.pay-actions {
  display: flex;
  gap: 20rpx;
  margin-bottom: 30rpx;
}

.action-btn {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 14px;
  border-radius: 12rpx;
  margin: 0;
}

.alipay {
  text-align: center;
  background-color: #1677ff;
  color: #ffffff;
}

.wechat {
  background-color: #07c160;
  color: #ffffff;
}

.pay-tips {
  font-size: 12px;
  color: #999999;
  line-height: 1.5;
}
</style>

